/**
 * 订单明细弹窗 - 数据穿透功能（优化版）
 */
import React from 'react';
import { X, Package, User, MapPin, Clock, DollarSign } from 'lucide-react';

interface Order {
  id: string;
  product: string;
  user: string;
  region: string;
  amount: number;
  time: string;
  status?: string;
  store?: string;
  quantity?: number;
  customerPhone?: string;
  address?: string;
}

interface OrderDetailModalProps {
  isOpen: boolean;
  onClose: () => void;
  orders: Order[];
  title?: string;
  showStatusFilter?: boolean;
  totalOrders?: number;
  refreshData?: () => void;
}

// 格式化时间显示
const formatTime = (timeStr: string): string => {
  try {
    // 如果是完整的时间戳字符串，尝试解析
    if (timeStr.includes('GMT') || timeStr.includes('T')) {
      const date = new Date(timeStr);
      if (!isNaN(date.getTime())) {
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${month}-${day} ${hours}:${minutes}`;
      }
    }
    // 如果已经是简单格式（如 "10:30"），直接返回
    return timeStr;
  } catch {
    return timeStr;
  }
};

const OrderDetailModal: React.FC<OrderDetailModalProps> = ({
  isOpen,
  onClose,
  orders,
  title = '订单明细',
  showStatusFilter = false,
  totalOrders = 0,
  refreshData
}) => {
  const [statusFilter, setStatusFilter] = React.useState('all');

  if (!isOpen) return null;

  // 计算总金额
  const totalAmount = orders.reduce((sum, order) => sum + order.amount, 0);

  // 根据状态筛选订单
  const filteredOrders = statusFilter === 'all'
    ? orders
    : orders.filter(order => order.status === statusFilter);

  // 获取所有唯一的订单状态
  const allStatuses = Array.from(new Set(orders.map(order => order.status).filter(Boolean)));

  // 处理状态筛选变更
  const handleStatusChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setStatusFilter(e.target.value);
  };

  // 处理刷新数据
  const handleRefresh = () => {
    if (refreshData) {
      refreshData();
    }
  };

  return (
    <div
      className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4"
      onClick={onClose}
    >
      <div
        className="bg-white rounded-2xl shadow-2xl w-full max-w-5xl max-h-[85vh] overflow-hidden flex flex-col animate-in fade-in zoom-in duration-200"
        onClick={(e) => e.stopPropagation()}
      >
        {/* 头部 - 优化样式 */}
        <div className="flex flex-col md:flex-row md:items-center justify-between p-6 border-b border-gray-200 bg-gradient-to-r from-blue-50 to-indigo-50 gap-4">
          <div className="flex-1">
            <h3 className="text-2xl font-bold text-gray-800 mb-1">{title}</h3>
            <p className="text-sm text-gray-600">
              显示 <span className="font-semibold text-blue-600">{filteredOrders.length}</span> 条订单
              {totalOrders > 0 && (
                <span className="ml-2">(共 {totalOrders} 条)</span>
              )}
              {totalAmount > 0 && (
                <span className="ml-4">
                  总金额: <span className="font-bold text-green-600">¥{totalAmount.toLocaleString()}</span>
                </span>
              )}
            </p>
          </div>
          <div className="flex items-center gap-3">
            {showStatusFilter && allStatuses.length > 0 && (
              <div className="relative">
                <select
                  value={statusFilter}
                  onChange={handleStatusChange}
                  className="appearance-none bg-white border border-gray-300 rounded-lg px-4 py-2 pr-10 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="all">全部状态</option>
                  {allStatuses.map(status => (
                    <option key={status} value={status}>{status}</option>
                  ))}
                </select>
                <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700">
                  <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                  </svg>
                </div>
              </div>
            )}
            {refreshData && (
              <button
                onClick={handleRefresh}
                className="p-2 hover:bg-white/80 rounded-lg transition-all hover:scale-110 active:scale-95"
                aria-label="刷新"
              >
                <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                </svg>
              </button>
            )}
            <button
              onClick={onClose}
              className="p-2 hover:bg-white/80 rounded-lg transition-all hover:scale-110 active:scale-95"
              aria-label="关闭"
            >
              <X size={22} className="text-gray-600" />
            </button>
          </div>
        </div>

        {/* 表头 - 新增 */}
        <div className="hidden md:grid md:grid-cols-12 gap-4 px-6 py-3 bg-gray-50 border-b border-gray-200 text-xs font-semibold text-gray-600 uppercase tracking-wider">
          <div className="col-span-3">商品</div>
          <div className="col-span-2">用户</div>
          <div className="col-span-2">地区</div>
          <div className="col-span-1">状态</div>
          <div className="col-span-1">店铺</div>
          <div className="col-span-1 text-right">金额</div>
          <div className="col-span-2 text-right">时间</div>
        </div>

        {/* 订单列表 - 优化滚动和样式 */}
        <div className="overflow-y-auto flex-1 scrollbar-thin">
          {/* 根据状态筛选后的空状态 */}
          {filteredOrders.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 text-gray-400">
              <Package size={48} className="mb-4 opacity-50" />
              <p className="text-lg">
                {statusFilter === 'all' ? '暂无订单数据' : `暂无${statusFilter}状态的订单`}
              </p>
              {statusFilter !== 'all' && (
                <button
                  onClick={() => setStatusFilter('all')}
                  className="mt-4 text-sm text-blue-600 hover:text-blue-800"
                >
                  查看全部订单
                </button>
              )}
            </div>
          ) : (
            <div className="divide-y divide-gray-100">
              {filteredOrders.map((order) => (
                <div
                  key={order.id}
                  className="p-5 hover:bg-gradient-to-r hover:from-blue-50/50 hover:to-indigo-50/50 transition-all duration-200 group"
                >
                  <div className="grid grid-cols-1 md:grid-cols-12 gap-4 items-center">
                    {/* 商品信息 */}
                    <div className="col-span-1 md:col-span-3 flex items-center gap-3">
                      <div className="p-2 bg-blue-100 rounded-lg group-hover:bg-blue-200 transition-colors">
                        <Package size={18} className="text-blue-600" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <span className="text-sm font-semibold text-gray-900 block truncate">
                          {order.product}
                        </span>
                        <span className="text-xs text-gray-500">订单 #{order.id.slice(-6)}</span>
                        {order.quantity && (
                          <span className="ml-2 text-xs text-gray-500">x{order.quantity}</span>
                        )}
                      </div>
                    </div>

                    {/* 用户信息 */}
                    <div className="col-span-1 md:col-span-2 flex items-center gap-3">
                      <div className="p-2 bg-green-100 rounded-lg group-hover:bg-green-200 transition-colors">
                        <User size={18} className="text-green-600" />
                      </div>
                      <span className="text-sm font-medium text-gray-700 truncate">{order.user}</span>
                    </div>

                    {/* 地区信息 */}
                    <div className="col-span-1 md:col-span-2 flex items-center gap-3">
                      <div className="p-2 bg-orange-100 rounded-lg group-hover:bg-orange-200 transition-colors">
                        <MapPin size={18} className="text-orange-600" />
                      </div>
                      <span className="text-sm text-gray-700 truncate">{order.region}</span>
                    </div>

                    {/* 订单状态 */}
                    <div className="col-span-1 md:col-span-1">
                      {order.status && (
                        <span className={`text-xs px-2 py-1 rounded-full font-medium ${getOrderStatusStyle(order.status)}`}>
                          {order.status}
                        </span>
                      )}
                    </div>

                    {/* 店铺信息 */}
                    <div className="col-span-1 md:col-span-1">
                      <span className="text-xs text-gray-600 truncate">{order.store || '-'}</span>
                    </div>

                    {/* 金额信息 */}
                    <div className="col-span-1 md:col-span-1 flex items-center justify-end md:justify-end gap-2">
                      <DollarSign size={16} className="text-green-600" />
                      <span className="text-base font-bold text-gray-900">
                        ¥{order.amount.toLocaleString()}
                      </span>
                    </div>

                    {/* 时间信息 */}
                    <div className="col-span-1 md:col-span-2 flex items-center justify-end md:justify-end gap-2">
                      <Clock size={14} className="text-gray-400" />
                      <span className="text-xs text-gray-500 font-mono">
                        {formatTime(order.time)}
                      </span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 底部 - 优化样式 */}
        <div className="p-5 border-t border-gray-200 bg-gray-50/80 backdrop-blur-sm">
          <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between mb-3 gap-2">
            <div className="text-sm text-gray-600">
              共 <span className="font-semibold text-gray-900">{filteredOrders.length}</span> 条订单
              {totalOrders > 0 && (
                <span className="ml-1">(总订单: {totalOrders})</span>
              )}
            </div>
            {totalAmount > 0 && (
              <div className="text-sm text-gray-600">
                合计: <span className="text-lg font-bold text-green-600">¥{totalAmount.toLocaleString()}</span>
              </div>
            )}
          </div>
          <div className="flex gap-3">
            {showStatusFilter && statusFilter !== 'all' && (
              <button
                onClick={() => setStatusFilter('all')}
                className="flex-1 px-6 py-3 bg-gray-200 text-gray-800 rounded-xl font-semibold hover:bg-gray-300 transition-all duration-200"
              >
                查看全部
              </button>
            )}
            <button
              onClick={onClose}
              className={`flex-1 px-6 py-3 bg-gradient-to-r ${showStatusFilter && statusFilter !== 'all' ? 'from-blue-500 to-indigo-600' : 'from-blue-600 to-indigo-700'} text-white rounded-xl font-semibold hover:from-blue-600 hover:to-indigo-700 transition-all duration-200 shadow-lg hover:shadow-xl transform hover:scale-[1.02] active:scale-[0.98]`}
            >
              关闭
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

// 根据订单状态返回对应的样式类名
const getOrderStatusStyle = (status: string): string => {
  switch (status) {
    case '待处理':
      return 'bg-yellow-100 text-yellow-800';
    case '已发货':
      return 'bg-blue-100 text-blue-800';
    case '已完成':
      return 'bg-green-100 text-green-800';
    case '已取消':
      return 'bg-red-100 text-red-800';
    default:
      return 'bg-gray-100 text-gray-800';
  }
};

export default OrderDetailModal;


